package com.hhxy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hhxy.handler.exception.CustomException;
import com.hhxy.mapper.TagMapper;
import com.hhxy.model.dto.AddTagDto;
import com.hhxy.model.dto.TagDto;
import com.hhxy.model.entity.ArticleTag;
import com.hhxy.model.entity.Tag;
import com.hhxy.model.vo.PageVo;
import com.hhxy.model.vo.TagVo;
import com.hhxy.service.ArticleTagService;
import com.hhxy.service.TagService;
import com.hhxy.utils.BeanCopyUtils;
import com.hhxy.utils.response.AppHttpCodeEnum;
import com.hhxy.utils.response.ResponseResult;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @author ghp
 * @description 针对表【tb_tag(标签)】的数据库操作Service实现
 * @createDate 2023-04-25 11:58:57
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag>
        implements TagService {

    @Resource
    private ArticleTagService articleTagService;

    /**
     * 分页条件查询标签信息
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public ResponseResult list(Integer pageNum, Integer pageSize, String name) {
        // 分页条件查询标签信息
        Page<Tag> page = new Page<>(pageNum, pageSize);
        this.page(page, new LambdaQueryWrapper<Tag>()
                .like(StringUtils.hasText(name), Tag::getName, name)
                .orderByDesc(Tag::getUpdateTime));
        // 封装VO
        List<TagVo> tagVoList = BeanCopyUtils.copyBeanList(page.getRecords(), TagVo.class);
        PageVo<TagVo> pageVo = new PageVo<>(tagVoList, page.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    /**
     * 根据标签id删除标签
     *
     * @param ids
     * @return
     */
    @Override
    public ResponseResult deleteByIds(Long[] ids) {
        // 判断该标签下是否有文章
        for (Long id : ids) {
            int count = articleTagService.count(new LambdaQueryWrapper<ArticleTag>()
                    .eq(ArticleTag::getTagId, id));
            if (count > 0) {
                // 该标签下有文章，不能直接删除
                throw new CustomException(AppHttpCodeEnum.CLIENT_TAG_ERROR);
            }
        }
        // 该标签下没有文章，则可以直接删除
        boolean flag = this.removeByIds(Arrays.asList(ids));
        if (!flag) {
            // 数据库服务出现了问题
            throw new CustomException(AppHttpCodeEnum.SERVICE_DELETE_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS_DELETE);
    }

    /**
     * 根据标签id查询标签
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult getTagById(Long id) {
        // 根据标签id查询对应的标签信息
        Tag tag = this.getById(id);
        // 封装VO
        TagVo tagVo = BeanCopyUtils.copyBean(tag, TagVo.class);
        return ResponseResult.okResult(tagVo);
    }

    /**
     * 更具标签id修改标签信息
     *
     * @param tagDto
     * @return
     */
    @Override
    public ResponseResult updateTagById(TagDto tagDto) {
        Tag tag = BeanCopyUtils.copyBean(tagDto, Tag.class);
        boolean flag = this.updateById(tag);
        if (!flag) {
            throw new CustomException(AppHttpCodeEnum.SERVICE_UPDATE_ERROR);
        }
        return ResponseResult.okResult();
    }

    /**
     * 新增标签
     *
     * @param addTagDto
     * @return
     */
    @Override
    public ResponseResult add(AddTagDto addTagDto) {
        Tag tag = BeanCopyUtils.copyBean(addTagDto, Tag.class);
        // 判断已被逻辑删除（is_delete=1）的记录是否已经存在了该记录
        Tag t = this.getBaseMapper().selectDeletedTagById(tag.getName());
        if (Objects.nonNull(t)) {
            // 新增的标签存在于已被逻辑删除的记录中，直接更新即可
            t.setName(tag.getName());
            t.setRemark(tag.getRemark());
            boolean flag = this.getBaseMapper().updateDeletedTagById(t);
            if (!flag){
                throw new CustomException(AppHttpCodeEnum.SERVICE_INSERT_ERROR);
            }
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS_INSERT);
        }

        // 新增的记录不在已被逻辑删除的记录中，直接新增即可
        boolean flag = this.save(tag);
        if (!flag) {
            throw new CustomException(AppHttpCodeEnum.SERVICE_INSERT_ERROR);
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS_INSERT);
    }

}




